package com.coder4j.starter.tools.util;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Keller
 * @date 2021-06-22 20:13:37
 * 文件工具类，读写文件
 */
public class FileUtils {

    /**
     * 写入文件
     *
     * @param filePath 文件路径
     * @param list     要写入的数据
     * @return
     */
    public static boolean write2File(String filePath, List<String> list) {
        return write2File(filePath, false, list);
    }

    /**
     * 写文件
     *
     * @param filePath 文件全路径，如果文件不存在，将创建新文件
     * @param isAppend 是否追加写文件 false 不追加，直接覆盖原文件；true 追加写，在原文件末尾追加
     * @param list     要保存的字符串列表，列表中的每一项单独写入一行
     * @return boolean
     */
    public static boolean write2File(String filePath, boolean isAppend, List<String> list) {
        OutputStreamWriter writer = null;
        BufferedWriter bufferedWriter = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            writer = new OutputStreamWriter(new FileOutputStream(file, isAppend), "UTF-8");
            bufferedWriter = new BufferedWriter(writer);
            for (String str : list) {
                bufferedWriter.write(str);
                bufferedWriter.newLine();
            }
            bufferedWriter.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                bufferedWriter.close();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取文件
     *
     * @param file
     * @param charsetName
     * @return
     */
    public static List<String> readFromFile(File file, String charsetName) {
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;

        String line = null;
        List<String> list = new ArrayList<>();
        try {

            if (!file.exists() || file.isDirectory()) {
                return list;
            }

            read = new InputStreamReader(new FileInputStream(file), charsetName);
            bufferedReader = new BufferedReader(read);

            while ((line = bufferedReader.readLine()) != null) {
                list.add(line);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return list;
        } finally {
            try {
                bufferedReader.close();
                read.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读文件
     *
     * @param filePath 文件全路径
     * @return List<String> 读取的文件内容
     */
    public static List<String> readFromFile(String filePath) {

        File file = new File(filePath);
        return readFromFile(file, "UTF-8");
    }

    public static List<String> scanFiles(String filePath) {
        List<String> list = new ArrayList<>();
        //根路径
        File root = new File(filePath);
        //根路径不存在
        if (!root.exists()) {
            return list;
        }
        //路径是个文件
        if (root.isFile()) {
            list.add(filePath);
            return list;
        }
        String[] array = root.list();
        if (array == null || array.length == 0) {
            return list;
        }

        //过滤出所有文件
        List<String> subFileList = Arrays.stream(array)
                .filter(item -> {
                    File file = new File(filePath + File.separatorChar + item);
                    return file.isFile();
                })
                .collect(Collectors.toList());
        for (String item : subFileList) {
            list.add(filePath + File.separatorChar + item);
        }


        //过滤出所有目录，进行递归
        List<String> subPathList = Arrays.stream(array)
                .filter(item -> {
                    File file = new File(filePath + File.separatorChar + item);
                    return file.isDirectory();
                })
                .collect(Collectors.toList());

        for (String subPath : subPathList) {
            list.addAll(scanFiles(filePath + File.separatorChar + subPath));
        }
        return list;
    }

    public static String getFileName(String filePath){
        return filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1);
    }

    /**
     * 获取文件后缀名
     * @param filePath
     * @return
     */
    public static String getSuffixName(String filePath){
        return filePath.substring(filePath.lastIndexOf("."));
    }

    public static void copy(String sourcePath, String destPah) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(new File(sourcePath));
            os = new FileOutputStream(new File(destPah));
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        }finally {
            is.close();
            os.close();
        }
    }

    public static void main(String[] args) {
        List<String> list = scanFiles("/Users/Keller/origin/keller/keller-starter-tools");
        System.out.println(JSON.toJSONString(list));
    }
}
